#include "gconfitem.h"

#include <QtCore/QDebug>
#include <MGConfItem>

#define DEBUG() qDebug() << __PRETTY_FUNCTION__ << __LINE__

class GConfItem::Private : public QObject
{
    Q_OBJECT
public:
    Private(GConfItem *parent);

    QString key;
    QVariant value;

private slots:
    void keyChanged(const QString &key);
    void valueChanged(const QVariant &value);
    void valueChanged();

private:
    GConfItem *q;
    MGConfItem *item;
};

GConfItem::Private::Private(GConfItem *parent)
    : QObject(parent)
    , q(parent)
    , item(0)
{
    connect(q, SIGNAL(keyChanged(QString)), this, SLOT(keyChanged(QString)));
    connect(q, SIGNAL(valueChanged(QVariant)), this, SLOT(valueChanged(QVariant)));
}

void GConfItem::Private::keyChanged(const QString &key)
{
    if (item) {
        disconnect(item);
        item->deleteLater();
        item = 0;
        q->setValue(QVariant());
    }
    if (!key.isNull()) {
        item = new MGConfItem(key, this);
        connect(item, SIGNAL(valueChanged()), this, SLOT(valueChanged()));
        q->setValue(item->value());
    }
}

void GConfItem::Private::valueChanged(const QVariant &value)
{
    item->set(value);
}

void GConfItem::Private::valueChanged()
{
    q->setValue(item->value());
}

GConfItem::GConfItem(QObject *parent)
    : QObject(parent)
    , d(new Private(this))
{
}

const QString &GConfItem::key() const
{
    return d->key;
}

void GConfItem::setKey(const QString &key)
{
    if (d->key == key) return;
    d->key = key;
    emit keyChanged(key);
}

const QVariant &GConfItem::value() const
{
    return d->value;
}

void GConfItem::setValue(const QVariant &value)
{
    if (d->value == value) return;
    d->value = value;
    emit valueChanged(value);
}

#include "gconfitem.moc"
